import axios from 'axios'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'

// 创建axios实例
const request = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    const appStore = useAppStore()
    
    // 添加token
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    
    // 显示加载状态
    appStore.setLoading(true)
    
    return config
  },
  (error) => {
    const appStore = useAppStore()
    appStore.setLoading(false)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    const appStore = useAppStore()
    appStore.setLoading(false)
    
    return response
  },
  (error) => {
    const appStore = useAppStore()
    const userStore = useUserStore()
    
    appStore.setLoading(false)
    
    // 处理不同的错误状态码
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          // 未授权，清除token并跳转到登录页
          userStore.logout()
          window.location.href = '/login'
          appStore.addNotification({
            type: 'error',
            title: '认证失败',
            message: '登录已过期，请重新登录'
          })
          break
          
        case 403:
          appStore.addNotification({
            type: 'error',
            title: '权限不足',
            message: data.message || '您没有权限执行此操作'
          })
          break
          
        case 404:
          appStore.addNotification({
            type: 'error',
            title: '资源不存在',
            message: data.message || '请求的资源不存在'
          })
          break
          
        case 422:
          // 表单验证错误
          if (data.errors) {
            const errorMessages = Object.values(data.errors).flat().join(', ')
            appStore.addNotification({
              type: 'error',
              title: '表单验证失败',
              message: errorMessages
            })
          }
          break
          
        case 500:
          appStore.addNotification({
            type: 'error',
            title: '服务器错误',
            message: data.message || '服务器内部错误，请稍后重试'
          })
          break
          
        default:
          appStore.addNotification({
            type: 'error',
            title: '请求失败',
            message: data.message || `请求失败 (${status})`
          })
      }
    } else if (error.request) {
      // 网络错误
      appStore.addNotification({
        type: 'error',
        title: '网络错误',
        message: '网络连接失败，请检查网络设置'
      })
    } else {
      // 其他错误
      appStore.addNotification({
        type: 'error',
        title: '请求错误',
        message: error.message || '请求发生未知错误'
      })
    }
    
    return Promise.reject(error)
  }
)

export default request